package com.ctgu.server.components.Interceptor;

import com.ctgu.server.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private static final List<String> ALLOWED_PATHS = Arrays.asList(
            "/server/user/key",
            "/server/user/login",
            "/server/user/captcha",
            "/server/user/check",
            "/register/user/",
            "/doc.html"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestPath = request.getRequestURI();
        if (requestPath.startsWith("/doc.html") || requestPath.startsWith("/webjars") || requestPath.startsWith("/swagger-resources")) {
            log.info("处理Knife4j接口文档请求，请求路径：{}", requestPath);
            return true;
        }
//        if(requestPath.startsWith("/static")){
//            log.info("静态资源请求！");
//            return true;
//        }
//        // 检查请求路径是否在允许的路径列表中，如果是，则允许通过拦截器
//        if (ALLOWED_PATHS.contains(requestPath)) {
//            return true;
//        }


//        String token = request.getHeader("Authorization");
//        // 检查是否存在令牌
//        if (token == null || token.isEmpty()) {
//
//            sendUnauthorizedResponse(response, "Missing token");
//            return false;
//        }
//        log.info("Authorization: "+token);
//
//        // 验证令牌是否有效
//        if (!JWTUtil.isValidToken(token)) {
//            sendUnauthorizedResponse(response, "Invalid token");
//            return false;
//        }

        // 验证通过，允许通过拦截器
        return true;
    }



    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\n" +
                "\t\"code\": 401\"\",\n" +
                "\t\"message\": \""+message+"\"\n" +
                "}");
    }
}
